package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.IParameterClient;
import com.heima.apis.behavior.IBehaviorClient;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.ApArticleCollectionConstants;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.RedisKeyConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.mess.ArticleVisitStreamMess;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleCollection;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.thread.ApThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service
@Transactional
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    // 单页最大加载的数字
    private final static short MAX_PAGE_SIZE = 50;

    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private CacheService cacheService;
    /**
     * 根据参数加载文章列表
     *
     * @param loadtype 1为加载更多  2为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {
        //1.校验参数
        Integer size = dto.getSize();
        if (size == null || size == 0) {
            size = 10;
        }
        size = Math.min(size, MAX_PAGE_SIZE);
        dto.setSize(size);

        //类型参数检验
        if (!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //文章频道校验
        if (StringUtils.isEmpty(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }

        //时间校验
        if (dto.getMaxBehotTime() == null) dto.setMaxBehotTime(new Date());
        if (dto.getMinBehotTime() == null) dto.setMinBehotTime(new Date());
        //2.查询数据
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadtype);

        //3.结果封装
        ResponseResult responseResult = ResponseResult.okResult(apArticles);
        return responseResult;
    }

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    ArticleFreemarkerServiceImpl articleFreemarkerService;

    /**
     * 保存app端相关文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveArticle(ArticleDto dto) {

        //        try {
        //            Thread.sleep(3000);
        //        } catch (InterruptedException e) {
        //            e.printStackTrace();
        //        }
        //1.检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);

        //2.判断是否存在id
        if (dto.getId() == null) {
            //2.1 不存在id  保存  文章  文章配置  文章内容

            //保存文章
            save(apArticle);

            //保存配置
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);

            //保存 文章内容
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.insert(apArticleContent);

        } else {
            //2.2 存在id   修改  文章  文章内容

            //修改  文章
            updateById(apArticle);

            //修改文章内容
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, dto.getId()));
            apArticleContent.setContent(dto.getContent());
            apArticleContentMapper.updateById(apArticleContent);
        }

        //异步调用 生成静态文件上传到minio中
        articleFreemarkerService.buildArticleToMinIO(apArticle, dto.getContent());


        //3.结果返回  文章的id
        return ResponseResult.okResult(apArticle.getId());
    }

    @Override
    public List<ApArticle> articleList(Map map) {
        LambdaQueryWrapper<ApArticle> articleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        String channelName = (String) map.get("channelName");
        articleLambdaQueryWrapper.eq(ApArticle::getChannelName, channelName);
        List<ApArticle> list = list(articleLambdaQueryWrapper);
        return list;
    }

    @Autowired
    RedisTemplate<String, String> redisTemplate;
    @Autowired
    private IBehaviorClient iBehaviorClient;
    @Autowired
    ApArticleCollectionServiceImpl apArticleCollectionService;

    @Override
    public ResponseResult articleBehavior(ArticleInfoDto dto) {
        //0.条件判断
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "缺少文章id");
        }
        //0.1从线程中拿用户id
        Integer apUserId = ApThreadLocalUtils.getUser().getId();
        //1判断文章是否存在
        LambdaQueryWrapper<ApArticle> apArticleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apArticleLambdaQueryWrapper.eq(ApArticle::getId, dto.getArticleId());
        ApArticle apArticle = getOne(apArticleLambdaQueryWrapper);
        //1.1文章不存在，则返回提示信息
        if (apArticle == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已经不存在");
        }
//TODO=======================================================================================================================
        //1.2文章存在
        Map<String, String> map = new HashMap<>();
        map.put("authorId", dto.getAuthorId().toString());
        map.put("articleId", dto.getArticleId().toString());
        //IParameterClient client = null;
        Boolean isLike = false;
        Boolean isLove = false;
        Boolean isFollow = false;
        Boolean isCollection = false;
        Integer readCount = 0;
        //1.2.1拿取是否收藏的数据
        //1.2.1.1redis中有数据，拿数据
        String redisKey = RedisKeyConstants.COLLECTION_REDIS_KEY_PREFIX + apUserId;
        Object collection =  redisTemplate.opsForHash().get(redisKey, dto.getArticleId().toString());
        if (collection != null) {
            isCollection = true;
        } else {
            //1.2.1.2redis中没有数据，则查询数据库
            LambdaQueryWrapper<ApArticleCollection> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(ApArticleCollection::getArticleId, dto.getArticleId());
            lambdaQueryWrapper.eq(ApArticleCollection::getUserId, apUserId);
            ApArticleCollection apArticleCollection = apArticleCollectionService.getOne(lambdaQueryWrapper);
            //1.2.1.2.1数据库中有数据
            if (apArticleCollection != null) {
                //1.2.1.2.1.1从数据库中拿数据，并存储到redis中
                if (apArticleCollection.getOperation().equals(ApArticleCollectionConstants.IS_COLLECTION)) {
                    //1.2.1.2.1.1.1收藏则保存在redis中
                    redisTemplate.opsForHash().put(redisKey, dto.getArticleId().toString(), apArticleCollection.getOperation().toString());
                    isCollection = true;
                } else {
                    //1.2.1.2.1.1.2取消收藏则删除redis中的数据
                    redisTemplate.opsForHash().delete(redisKey, dto.getArticleId().toString());
                    isCollection = false;
                }
            } else {
                //1.2.1.2.2数据库中没有数据
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "数据不存在");
            }
        }
        //TODO
        //1.2.2拿取是否点赞的数据
        //isLike = getParameter(map, client, isLike);
        isLove = (Boolean) iBehaviorClient.findLike(map).getData();
        //1.2.3拿取是否喜欢的数据
        isLove = (Boolean) iBehaviorClient.findIsUnLike(map).getData();
        //1.2.4拿取是否关注的数据
        // isFollow = getParameter(map, client, isFollow);
        //1.2.5拿取是否阅读的数据
        //readCount = getCount(map, client);
        //1.3填充属性
        fillArticleMessages(dto, isCollection, isLike, isLove, readCount, isFollow);
        return ResponseResult.okResult(dto);
//TODO=======================================================================================================================
    }

    /**
     * 获取参数
     * @param map
     * @param client
     * @param parameter
     * @return
     */
    /*private Boolean getParameter(Map<String, String> map, IParameterClient client, Boolean parameter) {
        Boolean flag = client.getParameter(map);
        if (flag != null){
            parameter = flag;
        }
        return parameter;
    }*/

    /**
     * 填充参数
     * @param dto
     * @param isCollection
     * @param isLike
     * @param isLove
     * @param readCount
     * @param isFollow
     */
    private void fillArticleMessages(ArticleInfoDto dto, Boolean isCollection, Boolean isLike, Boolean isLove, Integer readCount, Boolean isFollow) {
        dto.setIsCollection(isCollection);
        dto.setIsLike(isLike);
        dto.setIsLove(isLove);
        dto.setIsFollow(isFollow);
        dto.setReadCount(readCount);
    }

    /**
     * 获取阅读数
     * @param map
     * @param client
     * @return
     */
    private Integer getCount(Map<String, String> map, IParameterClient client) {
        return client.getCount(map);
    }

    /**
     * 更新文章的分值  同时更新缓存中的热点文章数据
     * @param mess
     */
    @Override
    public void updateScore(ArticleVisitStreamMess mess) {
        //1.更新文章的阅读、点赞、收藏、评论的数量
        ApArticle apArticle = updateArticle(mess);
        //2.计算文章的分值
        Integer score = computeScore(apArticle);
        score = score * 3;

        //3.替换当前文章对应频道的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());

        //4.替换推荐对应的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);

    }

    /**
     * 替换数据并且存入到redis
     * @param apArticle
     * @param score
     * @param s
     */
    private void replaceDataToRedis(ApArticle apArticle, Integer score, String s) {
        String articleListStr = cacheService.get(s);
        if (StringUtils.isNotBlank(articleListStr)) {
            List<HotArticleVo> hotArticleVoList = JSON.parseArray(articleListStr, HotArticleVo.class);

            boolean flag = true;

            //如果缓存中存在该文章，只更新分值
            for (HotArticleVo hotArticleVo : hotArticleVoList) {
                if (hotArticleVo.getId().equals(apArticle.getId())) {
                    hotArticleVo.setScore(score);
                    flag = false;
                    break;
                }
            }

            //如果缓存中不存在，查询缓存中分值最小的一条数据，进行分值的比较，如果当前文章的分值大于缓存中的数据，就替换
            if (flag) {
                if (hotArticleVoList.size() >= 30) {
                    hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
                    HotArticleVo lastHot = hotArticleVoList.get(hotArticleVoList.size() - 1);
                    if (lastHot.getScore() < score) {
                        hotArticleVoList.remove(lastHot);
                        HotArticleVo hot = new HotArticleVo();
                        BeanUtils.copyProperties(apArticle, hot);
                        hot.setScore(score);
                        hotArticleVoList.add(hot);
                    }
                } else {
                    HotArticleVo hot = new HotArticleVo();
                    BeanUtils.copyProperties(apArticle, hot);
                    hot.setScore(score);
                    hotArticleVoList.add(hot);
                }
            }
            //缓存到redis
            hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
            cacheService.set(s, JSON.toJSONString(hotArticleVoList));

        }
    }

    /**
     * 计算文章的具体分值
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        if(apArticle.getLikes() != null){
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if(apArticle.getViews() != null){
            score += apArticle.getViews();
        }
        if(apArticle.getComment() != null){
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if(apArticle.getCollection() != null){
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }

    /**
     * 更新文章行为数量
     * @param mess
     */
    private ApArticle updateArticle(ArticleVisitStreamMess mess) {
        ApArticle apArticle = getById(mess.getArticleId());
        apArticle.setCollection(apArticle.getCollection()==null?0:apArticle.getCollection()+mess.getCollect());
        apArticle.setComment(apArticle.getComment()==null?0:apArticle.getComment()+mess.getComment());
        apArticle.setLikes(apArticle.getLikes()==null?0:apArticle.getLikes()+mess.getLike());
        apArticle.setViews(apArticle.getViews()==null?0:apArticle.getViews()+mess.getView());
        updateById(apArticle);
        return apArticle;
    }

    /**
     * 加载文章列表
     * @param dto
     * @param type      1 加载更多   2 加载最新
     * @param firstPage true  是首页  flase 非首页
     * @return
     */
    @Override
    public ResponseResult load2(ArticleHomeDto dto, Short type, boolean firstPage) {
        if(firstPage){
            String jsonStr = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if(StringUtils.isNotBlank(jsonStr)){
                List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonStr, HotArticleVo.class);
                ResponseResult responseResult = ResponseResult.okResult(hotArticleVoList);
                return responseResult;
            }
        }
        return load(type,dto);
    }
}